package com.plugin.manage.service.impl;

import com.plugin.manage.common.RespObj;
import com.plugin.manage.mapper.*;
import com.plugin.manage.service.IElderService;
import com.plugin.core.model.entity.ElderHealthCheckException;
import com.plugin.core.model.entity.ElderActivityNotice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

/**
 * 长者看板服务实现类
 * 
 * @author mark
 * @date 2025-07-26
 */
@Service
@Slf4j
public class ElderServiceImpl implements IElderService {

    @Autowired
    private ElderInfoMapper elderInfoMapper;

    @Autowired
    private ElderRoomMapper elderRoomMapper;

    @Autowired
    private ElderBedsMapper elderBedsMapper;

    @Autowired
    private ElderHealthCheckExceptionMapper elderHealthCheckExceptionMapper;

    @Autowired
    private ElderActivityNoticeMapper elderActivityNoticeMapper;

    @Autowired
    private ElderCarePlanMapper elderCarePlanMapper;

    @Override
    public RespObj<?> getSelfCareAbilityPercentage() {

        Map<String, Object> percentageData = new HashMap<>();

        try {
            // 获取总人数
            Long totalCount = elderInfoMapper.getTotalCount();
            if (totalCount == 0) {
                return new RespObj<>().success("暂无数据");
            }

            // 获取按自理能力分组的统计数据
            List<Map<String, Object>> stats = elderInfoMapper.getSelfCareAbilityStats();
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalCount", totalCount);
            

            
            for (Map<String, Object> stat : stats) {
                Integer selfCareAbility = (Integer) stat.get("self_care_ability");
                Long count = ((Number) stat.get("count")).longValue();
                
                // 计算百分比，保留2位小数
                BigDecimal percentage = BigDecimal.valueOf(count)
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(totalCount), 2, RoundingMode.HALF_UP);
                
                Map<String, Object> levelData = new HashMap<>();
                levelData.put("count", count);
                levelData.put("percentage", percentage);
                
                percentageData.put(String.valueOf(selfCareAbility != null ? selfCareAbility : 0), levelData);
            }
            
            result.put("data", percentageData);
            
            return new RespObj<>().success(result);
            
        } catch (Exception e) {
            log.error("获取自理能力等级百分比统计失败", e);
            return new RespObj<>().failure("查询失败：" + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getCareLevelPercentage() {
        try {
            // 获取总人数
            Long totalCount = elderInfoMapper.getTotalCount();
            if (totalCount == 0) {
                return new RespObj<>().success("暂无数据");
            }

            // 获取按护理等级分组的统计数据
            List<Map<String, Object>> stats = elderInfoMapper.getCareLevelStats();
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalCount", totalCount);
            
            Map<String, Object> percentageData = new HashMap<>();
            
            for (Map<String, Object> stat : stats) {
                Integer careLevel = (Integer) stat.get("care_level");
                Long count = ((Number) stat.get("count")).longValue();
                
                // 计算百分比，保留2位小数
                BigDecimal percentage = BigDecimal.valueOf(count)
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(totalCount), 2, RoundingMode.HALF_UP);
                
                Map<String, Object> levelData = new HashMap<>();
                levelData.put("count", count);
                levelData.put("percentage", percentage);
                
                percentageData.put(String.valueOf(careLevel != null ? careLevel : 0), levelData);
            }
            
            result.put("data", percentageData);
            
            return new RespObj<>().success(result);
            
        } catch (Exception e) {
            log.error("获取护理等级百分比统计失败", e);
            return new RespObj<>().failure("查询失败：" + e.getMessage());
        }
    }


    @Override
    public Map<String, Object> getBedOccupancyStatistics() {
        try {
            // 获取总床位数（所有房间的床位数之和）
            Long totalBeds = elderBedsMapper.countBeds();
            if (totalBeds == 0) {
                return null;
            }

            // 获取已入住床位数（room_status = 1 的房间床位数之和）
            Long occupiedBeds = elderBedsMapper.countAvailableBeds();
            
            // 计算入住率百分比，保留2位小数
            BigDecimal occupancyRate = BigDecimal.valueOf(occupiedBeds)
                .multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(totalBeds), 2, RoundingMode.HALF_UP);
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalBeds", totalBeds);
            result.put("occupiedBeds", occupiedBeds);
            result.put("availableBeds", totalBeds - occupiedBeds);
            result.put("occupancyRate", occupancyRate);
            
            log.info("床位入驻统计查询成功：总床位{}，已入住{}，入住率{}%", totalBeds, occupiedBeds, occupancyRate);
            
            return result;
            
        } catch (Exception e) {
            log.error("获取床位入驻统计失败", e);
            return null;
        }
    }

    @Override
    public RespObj<?> getHealthCheckExceptions() {
        try {
            log.info("查询所有健康检查异常记录");
            
            // 调用mapper查询所有数据
            List<ElderHealthCheckException> exceptions = elderHealthCheckExceptionMapper.getHealthCheckExceptionsByConditions(
                    null, null, null, null, null);
            
            log.info("健康检查异常记录查询成功，共查询到{}条记录", exceptions.size());
            
            return new RespObj<>().success(exceptions);
            
        } catch (Exception e) {
            log.error("查询健康检查异常记录失败", e);
            return new RespObj<>().failure("查询健康检查异常记录失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getCarePlanRecords() {
        try {
            log.info("查询所有护理计划记录");

            // 调用mapper查询所有护理计划记录
            List<Map<String, Object>> records = elderCarePlanMapper.getCarePlanRecords();
            
            log.info("查询到护理计划记录数量: {}", records.size());
            return new RespObj<>().success(records);
            
        } catch (Exception e) {
            log.error("查询护理计划记录失败", e);
            return new RespObj<>().failure("查询护理计划记录失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getActivities() {
        try {
            log.info("查询所有活动通知记录");

            // 调用mapper查询所有活动通知记录
            List<ElderActivityNotice> activities = elderActivityNoticeMapper.selectActivityList();
            
            log.info("活动通知记录查询成功，共查询到{}条记录", activities.size());
            
            return new RespObj<>().success(activities);
            
        } catch (Exception e) {
            log.error("查询活动通知记录失败", e);
            return new RespObj<>().failure("查询活动通知记录失败: " + e.getMessage());
        }
    }
}
